# api_5001.py
# Create by GF 2025-05-10 23:51

# Python 3 Standard Libraries.
import io
import os
# ..................................................
import flask
# ..................................................
import proxy_openai_api_202505

# ##################################################

SIMILAR_TO_OPENAI_API_BASE_URL = "https://spark-api-open.xf-yun.com/v1"
                               # "https://spark-api-open.xf-yun.com/v1"
                               # "https://dashscope.aliyuncs.com/compatible-mode/v1"

# ##################################################

app = flask.Flask(__name__)

# ##################################################

@app.route("/v1", methods=["GET"])
def api_proxy_openai_v1():

    return '', 200

@app.route("/v1/favicon.ico", methods=["GET"])
def api_proxy_openai_v1_favicon_ico():

    return '', 200

@app.route("/v1/models", methods=["GET"])
def api_proxy_openai_v1_models():

    received_api_key = flask.request.headers.get("Authorization", '')
    # ..............................................
    if (received_api_key == ''):
        return flask.jsonify({"error": "missing api key"}), 401
    # ..............................................
    this_proxy_openai_api = proxy_openai_api_202505.proxy_openai_api()
    this_proxy_openai_api.url.update(f"{SIMILAR_TO_OPENAI_API_BASE_URL}/models")
    this_proxy_openai_api.headers.update({"Authorization": received_api_key}).update({"Content-Type": "application/json"})
    # ..............................................
    rps_dict = this_proxy_openai_api.get()
    # ..............................................
    return flask.jsonify(rps_dict), 200

@app.route("/v1/chat/completions", methods=["POST"])
def api_proxy_openai_v1_chat_completions():

    # Example:
    # - curl -H "Content-Type: application/json" \
    # -      -H "Authorization: Bearer please-enter-openai-api-key" \
    # -      -X POST \
    # -      -d '{"messages": [{"role": "user", "content": "Can you here me?"}]}' \
    # -      http://127.0.0.1:5001/v1/chat/completions
    # Returns:
    # - {'code': 0,
    # -  'message': 'Success',
    # -  'sid': 'cha000bc275@dx196bad449ab9a4b532',
    # -  'choices': [{'message': {'role': 'assistant', 'content': 'Can I help you?'},
    # -               'index': 0}],
    # -  'usage': {'prompt_tokens': 5, 'completion_tokens': 5, 'total_tokens': 10}}

    received_api_key = flask.request.headers.get("Authorization", '')
    # ..............................................
    if (received_api_key == ''):
        return flask.jsonify({"error": "missing api key"}), 401
    # ..............................................
    received_model    = flask.request.json.get("model",    [])
    received_messages = flask.request.json.get("messages", [])
    received_stream   = flask.request.json.get("stream",   False)
    # ..............................................
    try:
        this_proxy_openai_api = proxy_openai_api_202505.proxy_openai_api()
        this_proxy_openai_api.url.update(f"{SIMILAR_TO_OPENAI_API_BASE_URL}/chat/completions")
        this_proxy_openai_api.headers.update({"Authorization": received_api_key}).update({"Content-Type": "application/json"})
        this_proxy_openai_api.json.update({"model":  received_model})
        this_proxy_openai_api.json.update({"stream": received_stream})
        # ..........................................
        this_proxy_openai_api.json.update({"messages": received_messages})
        # ..........................................
        if (received_stream == True):
            rps_iter = this_proxy_openai_api.post()
            # 流式响应处理
            def generate():
                for chunk in rps_iter:
                    if chunk:
                        yield chunk
            # ......................................
            # OpenAI API 202505 的流式响应通常使用 Server-Sent Events (SSE),
            # 即 text/event-stream 类型,
            # 每个数据块以 "data: " 开头, 后跟 JSON 数据, 并以两个换行符结束
            return flask.Response(generate(), content_type="text/event-stream")
        else:
            rps_dict = this_proxy_openai_api.post()
            # ......................................
            return flask.jsonify(rps_dict), 200
    except Exception as e:
        return flask.jsonify({"error": str(e)}), 500

if __name__ == '__main__':

#   app.run(host="0.0.0.0", port=5001, debug=True)  # 调试模式
    app.run(host="0.0.0.0", port=5001)

# EOF Signed by GF.
